package com.sinping.qh.service.app.noticebook.impl;

import com.google.common.collect.Lists;
import com.sinping.qh.api.support.FrontPage;
import com.sinping.qh.api.support.ResDtoUtil;
import com.sinping.qh.domain.noticebook.NoticeBookDomain;
import com.sinping.qh.domain.records.HiddendangerRecord;
import com.sinping.qh.domain.records.RectifyReviewDomain;
import com.sinping.qh.dto.app.noticebook.NoticeBookByAppDTO;
import com.sinping.qh.dto.app.records.HiddendangerByAppDTO;
import com.sinping.qh.dto.app.records.HiddendangerNoticeBookByAppDto;
import com.sinping.qh.dto.app.records.HiddendangerNoticeBookGroupByAppDto;
import com.sinping.qh.dto.app.records.RectifyReviewByAppDTO;
import com.sinping.qh.dto.common.CommonDTO;
import com.sinping.qh.dto.mongo.auth.UserSessionDTO;
import com.sinping.qh.query.base.AggregateParams;
import com.sinping.qh.repository.mongo.RectifyReviewRepository;
import com.sinping.qh.repository.mongo.noticebook.impl.NoticeBookRepositoryImpl;
import com.sinping.qh.repository.mongo.user.UserLaboratoryRepository;
import com.sinping.qh.service.MongoManager;
import com.sinping.qh.service.app.noticebook.INoticeBookServiceApp;
import com.sinping.qh.service.base.BaseService;
import com.sinping.qh.utils.mapper.BeanMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author jiahuaiqing
 * @create 2018/6/9
 */
@Service
public class NoticeBookServiceAppImpl extends BaseService implements INoticeBookServiceApp {

    @Autowired
    MongoManager mongoManager;

    @Autowired
    NoticeBookRepositoryImpl noticeBookRepositoryImpl;

    @Autowired
    RectifyReviewRepository rectifyReviewRepository;

    @Autowired
    UserLaboratoryRepository userLaboratoryRepository;

    @Value(value = "${qh.upload.filePath}")
    private String filePath;
    @Value(value = "${qh.upload.urlPath}")
    private String urlPath;

    @Override
    public FrontPage findPage(FrontPage frontPage, UserSessionDTO userSessionDto) {

        Sort sort;
        if (StringUtils.isNotBlank(frontPage.getProp()) && StringUtils.isNotBlank(frontPage.getOrder())) {
            if (frontPage.getOrder().equals("asc")) {
                sort = new Sort(Sort.Direction.ASC, frontPage.getProp());
            } else {
                sort = new Sort(Sort.Direction.DESC, frontPage.getProp());
            }
        } else {
            sort = new Sort(Sort.Direction.DESC, "gmt_created");
        }

        Map<String, Object> condition = frontPage.getCondition();

        //查询条件
        PageRequest page = new PageRequest(frontPage.getPage() - 1, frontPage.getSize(), sort);


        List<String> unitIDLists=
                getUnitIDLists(userLaboratoryRepository,(userSessionDto.getUserInfo().getId()));

        List<String> labIDLists=
                getLabIDLists(userLaboratoryRepository,(userSessionDto.getUserInfo().getId()));


        List<NoticeBookByAppDTO> rsByPage = noticeBookRepositoryImpl.findPageByUniting(condition, unitIDLists,labIDLists, page, NoticeBookDomain.class, NoticeBookByAppDTO.class);

        List<NoticeBookByAppDTO> rsByNoPage = noticeBookRepositoryImpl.findPageByUniting(condition, unitIDLists,labIDLists, null, NoticeBookDomain.class, NoticeBookByAppDTO.class);

        Page<NoticeBookByAppDTO> pages = new PageImpl<>(rsByPage, page, rsByNoPage.size());
        //pdf添加urlPath
        //frontPage = ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(pages, NoticeBookByAppDTO.class, frontPage);
        List<NoticeBookByAppDTO> contentList = pages.getContent();
        List<NoticeBookByAppDTO> copyPagesContent = new ArrayList<>();
        for (NoticeBookByAppDTO dto : contentList) {
            if (StringUtils.isNotBlank(dto.getNoticeAttachPath())) {
                dto.setNoticeAttachPath(urlPath + dto.getNoticeAttachPath());
            }
            copyPagesContent.add(dto);
        }
        List apiOrders = BeanMapper.mapList(copyPagesContent, NoticeBookByAppDTO.class);
        long totalPages = pages.getTotalPages();
        frontPage.setTotal((int) pages.getTotalElements());
        frontPage.setPages((int) totalPages);
        frontPage.setRecords(apiOrders);
        return frontPage;

//        //查询条件
//        NoticeBookQuery noticeBookQuery = new NoticeBookQuery();
//        PageRequest page = new PageRequest(frontPage.getPage() - 1, frontPage.getSize(), sort);
//        Page<NoticeBookDomain> noticeBookDomains = mongoManager.findPage(noticeBookQuery, page, NoticeBookDomain.class);
//
//        ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(noticeBookDomains, NoticeBookByAppDTO.class, frontPage);
//        return frontPage;

    }

    @Override
    public List<HiddendangerNoticeBookGroupByAppDto> findUnitByHiddenDangerIds(List<String> hiddenDangerIds, UserSessionDTO userSessionDto) {
        //"check_lab_id", "check_unit_id", "check_unit", "check_building", "check_lab", "check_room"
        //分组条件
        List<String> groupParams = Lists.newArrayList("check_building_id", "check_building", "check_lab_id", "check_lab", "check_room");
        AggregateParams aggregateParams = new AggregateParams();

        List<HiddendangerNoticeBookGroupByAppDto> appList = noticeBookRepositoryImpl.findUnitByHiddenDangerIds(hiddenDangerIds, groupParams, aggregateParams, HiddendangerRecord.class, HiddendangerNoticeBookGroupByAppDto.class);
        for (HiddendangerNoticeBookGroupByAppDto appDto : appList) {
            String checkLabId = appDto.getCheckLabId();
            if (StringUtils.isNotBlank(checkLabId)) {
                appDto.setType("1");
            } else {
                appDto.setType("0");
            }
        }
        return appList;
    }

    /**
     * 查询通知书中，实验室或者楼宇中，的隐患记录
     *
     * @param hiddendangerNoticeBookByAppDto
     * @param userSessionDto
     * @return
     */
    @Override
    public List<HiddendangerByAppDTO> findHiddenDangerRecords(HiddendangerNoticeBookByAppDto hiddendangerNoticeBookByAppDto, UserSessionDTO userSessionDto) {
        List<String> hiddenDangerIds = hiddendangerNoticeBookByAppDto.getHiddenDangerIds();
        String type = hiddendangerNoticeBookByAppDto.getType();
        String params = null;
        //综合检查
        if (type.equals("0")) {
            params = hiddendangerNoticeBookByAppDto.getCheckBuildingId();
        }

        //实验室检查
        if (type.equals("1")) {
            params = hiddendangerNoticeBookByAppDto.getCheckLabId();
        }

        List<HiddendangerByAppDTO> hiddendangerByAppDTOS = noticeBookRepositoryImpl.findHiddenDangerRecords(hiddenDangerIds, type, params, HiddendangerRecord.class, HiddendangerByAppDTO.class);

        //把整改复查信息给添加到隐患记录中
        for (HiddendangerByAppDTO hiddendangerByAppDTO : hiddendangerByAppDTOS) {

            List<RectifyReviewDomain> rectifyReviewDomainList =
                    rectifyReviewRepository.findAllByHiddenDangerIdOrderByGmtModifiedAsc(hiddendangerByAppDTO.getId());

            List<RectifyReviewByAppDTO> hiddendangerByAppDTOList = Lists.newArrayList();
            for (RectifyReviewDomain rectifyReviewDomain : rectifyReviewDomainList) {

                RectifyReviewByAppDTO rectifyReviewByAppDTO =
                        BeanMapper.map(rectifyReviewDomain, RectifyReviewByAppDTO.class);
                hiddendangerByAppDTOList.add(rectifyReviewByAppDTO);

            }
            hiddendangerByAppDTO.setItems(hiddendangerByAppDTOList);
        }

        return hiddendangerByAppDTOS;
    }
}
